package com.suhuamo.thread.pool;

import sun.misc.Queue;

/**
 * @author yuanchuncheng
 * @slogan yscz
 * @date 2024-07-19
 * @description 自定义线程池
 */
public class ThreadPool implements Runnable {

    /**
     * 真正启用的线程
     * @version 1.0
     * @author yuanchuncheng
     */
    private Thread thread = new Thread(this);

    {
        thread.start();
    }

    private Queue<Runnable> taskQueue = new Queue<>();

    /**
     * 当前线程池的运行状态
     * @version 1.0
     * @author yuanchuncheng
     */
    private boolean running = true;

    /**
     * 添加任务
     * @param task
     * @return void
     * @version 1.0
     * @author yuanchuncheng
     */
    public void addTask(Runnable task)
    {
        taskQueue.enqueue(task);
    }

    /**
     * 停止线程池【强制的，没完成的任务也不要了】
     * @param
     * @return void
     * @version 1.0
     * @author yuanchuncheng
     */
    public void terminal() {
        running = false;
    }


    @lombok.SneakyThrows
    @Override
    public void run() {
        while(running)
        {
            Runnable dequeue = null;
            try {
                dequeue = taskQueue.dequeue();
            } catch (InterruptedException e) {
                continue;
            }
            if(null == dequeue) {
                Thread.sleep(10);
            } else {
                System.out.println("线程池执行任务开始");
                dequeue.run();
            }
        }
    }


}
